<template>
  <div class="order-list-container">
    <div class="order-list-card">
      <div class="search-bar">
        <el-input
          v-model="searchQuery"
          placeholder="搜索订单..."
          prefix-icon="el-icon-search"
          clearable
          @clear="handleSearchClear"
          @input="handleSearch">
        </el-input>
      </div>

      <el-table :data="filteredOrders" style="width: 100%">
        <el-table-column prop="id" label="订单号" width="180"></el-table-column>
        <el-table-column prop="course" label="课程名称"></el-table-column>
        <el-table-column prop="price" label="价格" width="120"></el-table-column>
        <el-table-column prop="date" label="日期" width="120"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280">
          <template slot-scope="scope">
            <div class="button-group">
              <el-button
                size="mini"
                type="primary"
                @click="viewDetail(scope.row)">查看详情</el-button>
              <el-button
                size="mini"
                type="danger"
                @click="deleteOrder(scope.row)">删除</el-button>
              <el-button
                v-if="scope.row.status === '已完成'"
                size="mini"
                type="success"
                @click="studyCourse(scope.row)">立即学习</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
export default {
  name: 'OrderList',
  data() {
    return {
      searchQuery: '',
      originalOrders: []
    }
  },
  computed: {
    orders() {
      return this.$store.state.orders;
    },
    filteredOrders() {
      if (!this.searchQuery) {
        return this.orders;
      }
      const query = this.searchQuery.toLowerCase();
      return this.orders.filter(order => 
        order.id.toLowerCase().includes(query) || 
        order.course.toLowerCase().includes(query)
      );
    }
  },
  created() {
    this.originalOrders = [...this.orders];
  },
  methods: {
    deleteOrder(order) {
      this.$confirm('确定要删除订单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('deleteOrder', order.id);
        this.$message.success('订单已删除');
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    getStatusTagType(status) {
      const map = {
        '待支付': 'warning',
        '已完成': 'success',
        '已取消': 'danger'
      }
      return map[status] || ''
    },
    viewDetail(order) {
      this.$router.push(`/dashboard/orders/${order.id}`)
    },
    handleSearch() {
      // 搜索逻辑已通过计算属性实现
    },
    handleSearchClear() {
      this.searchQuery = ''
    },
    studyCourse(order) {
      // 从课程名称中提取课程ID
      const courseMatch = /(\d+)/.exec(order.course);
      if (courseMatch) {
        const courseId = parseInt(courseMatch[1]);
        // 添加到已购买课程列表，确保能通过CourseStudy组件的判断
        if (!this.$store.getters.isCourseAlreadyPurchased(courseId)) {
          this.$store.dispatch('addPurchasedCourse', {
            id: courseId,
            name: order.course,
            purchaseDate: order.date
          });
        }
        // 跳转到课程学习页面
        this.$router.push(`/dashboard/study/${courseId}`);
      } else {
        // 如果无法识别课程ID，尝试使用课程名称匹配
        if (order.course.includes('Vue.js入门')) {
          const courseId = 1;
          if (!this.$store.getters.isCourseAlreadyPurchased(courseId)) {
            this.$store.dispatch('addPurchasedCourse', {
              id: courseId,
              name: order.course,
              purchaseDate: order.date
            });
          }
          this.$router.push(`/dashboard/study/${courseId}`);
        } else if (order.course.includes('Element UI')) {
          const courseId = 2;
          if (!this.$store.getters.isCourseAlreadyPurchased(courseId)) {
            this.$store.dispatch('addPurchasedCourse', {
              id: courseId,
              name: order.course,
              purchaseDate: order.date
            });
          }
          this.$router.push(`/dashboard/study/${courseId}`);
        } else {
          this.$message.warning('无法识别课程ID，请联系客服');
        }
      }
    }
  }
}
</script>

<style scoped>
.order-list-container {
  height: 100%;
  padding: 20px;
}

.order-list-card {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
  width: 300px;
}

.button-group {
  display: flex;
  flex-wrap: nowrap;
  gap: 5px;
}

.button-group .el-button {
  margin-left: 0;
  padding: 7px 10px;
}
</style>